package com.xiaohong.file.controller;

import com.xiaohong.file.interceptor.TokenRequestInterceptor;
import com.xiaohong.file.pojo.FastDFSFile;
import com.xiaohong.file.utils.FastDFSUtils;
import com.xiaohong.user.feign.UserFeign;
import entity.Result;
import entity.StatusCode;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Autowired
    private UserFeign userFeign;

   /* @GetMapping("/test")
//    @GlobalTransactional
    public void toUser(HttpServletRequest httpServletRequest) {
        // 加入令牌
        TokenRequestInterceptor.token = httpServletRequest.getHeader("Authorization");
        userFeign.findById("xiaohong");
        System.out.println("调用用户微服务成功！");
    }*/


    /**
     * 设置用户头像
     * @param file
     * @return
     */
//    @PostMapping(value = "/photo")
//    @PreAuthorize("hasAnyAuthority('user','admin')")
//    public Result SetHeadPic(@RequestParam(value = "file") MultipartFile file, HttpServletRequest httpServletRequest){
//        try {
//            System.out.println(file.getName());
//            //获取请求头里的token,待会feign时候用
//            TokenRequestInterceptor.token = httpServletRequest.getHeader("Authorization");
//            //获取请求头用户令牌信息
//            Map<String, Object> userInfo = TokenDecode.getUserInfo();
//            //获取用户名
//            String username = (String) userInfo.get("username");
//            //判断用户头像是否为空
//            User user = userFeign.findByOneSelf(username).getData();
//            if (!StringUtils.isEmpty(user.getHeadPic())){
//                //不为空先删除再添加
//                Result result = deleteFile(user.getHeadPic());
//                if (result.isFlag()){
//                    //更新头像
//                    String url = (String) uploadFile(file).getData();
//                    //将头像地址存储到数据库中
//                    user.setHeadPic(url);
//                    userFeign.updateByOneSelf(user);
//                    return new Result(true,StatusCode.OK,"设置头像完成！",url);
//                }else {
//                    return new Result(false,StatusCode.ERROR,"设置头像失败！");
//                }
//            }
//            //更新头像
//            String url = (String) uploadFile(file).getData();
//            //将头像地址存储到数据库中
//            user.setHeadPic(url);
//            userFeign.updateByOneSelf(user);
//            return new Result(true,StatusCode.OK,"设置头像完成！",url);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false,StatusCode.ERROR,"设置头像失败！");
//        }
//    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value ="/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PreAuthorize("hasAnyAuthority('user','admin')")
    public Result uploadFile(@RequestPart(value = "file") MultipartFile file) throws Exception {
        try {
            // 封装文件信息
            FastDFSFile fastDFSFile = new FastDFSFile(
                    file.getOriginalFilename(), // 文件名 1.jpg
                    file.getBytes(),  //文件字节数组
                    StringUtils.getFilenameExtension(file.getOriginalFilename()) //获取文件扩展名
            );

            String[] upLoad = FastDFSUtils.upLoad(fastDFSFile);
            // 拼接访问地址
//            String url = FastDFSUtils.getTrackerInfo()+"/"+upLoad[0]+"/"+upLoad[1];
            String url = "http://file.xiaohong.work/"+upLoad[0]+"/"+upLoad[1];
            return new Result(true, StatusCode.OK,"文件上传成功",url);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }


    /**
     * 上传文件(带下标)
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value ="/index/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PreAuthorize("hasAnyAuthority('user','admin')")
    public Result uploadFile(@RequestPart(value = "file") MultipartFile file, @RequestParam(value = "index") Integer index) throws Exception {
        try {
            // 封装文件信息
            FastDFSFile fastDFSFile = new FastDFSFile(
                    file.getOriginalFilename(), // 文件名 1.jpg
                    file.getBytes(),  //文件字节数组
                    StringUtils.getFilenameExtension(file.getOriginalFilename()) //获取文件扩展名
            );

            String[] upLoad = FastDFSUtils.upLoad(fastDFSFile);
            // 拼接访问地址
//            String url = FastDFSUtils.getTrackerInfo()+"/"+upLoad[0]+"/"+upLoad[1];
            String url = "http://file.xiaohong.work/"+upLoad[0]+"/"+upLoad[1];
            HashMap<String, Object> map = new HashMap<>();
            map.put("url", url);
            map.put("index",index);
            return new Result(true, StatusCode.OK,"文件上传成功",map);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }

    /**
     * 文件下载
     * @param fileUrl
     * @param downloadUrl
     * @return
     * @throws Exception
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @PostMapping(value = "/download")
    public Result downloadFile(String fileUrl, String downloadUrl) {
        try {
            fileUrl = fileUrl.split("xiaohong/")[1];
            InputStream downLoad = FastDFSUtils.downLoad("xiaohong", fileUrl);

            // 将文件写入本地磁盘
            //获取文件名
            String[] strings = fileUrl.split("/");
            if (!downloadUrl.endsWith("\\")){
                downloadUrl += "\\";
            }
            FileOutputStream outputStream = new FileOutputStream(downloadUrl+strings[strings.length-1]);

            //定义一个缓冲区
            byte[] buffer = new byte[1024];
            while (downLoad.read(buffer) != -1){
                outputStream.write(buffer);
            }
            outputStream.flush();
            outputStream.close();
            downLoad.close();

            return new Result(true, StatusCode.OK,"文件下载成功");
        }catch (Exception e){
            return new Result(true, StatusCode.OK,"文件下载失败或文件已删除");
        }

    }

    /**
     * 文件删除
     * @param fileUrl
     * @return
     * @throws Exception
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @DeleteMapping(value = "/delete")
    public Result deleteFile(@RequestParam(value = "fileUrl") String fileUrl) {
        try {
            fileUrl = fileUrl.split("xiaohong/")[1];
            FastDFSUtils.deleteFile("xiaohong",fileUrl);
            return new Result(true, StatusCode.OK,"文件删除成功！");
        }catch (Exception e){
            return new Result(false, StatusCode.REMOTEERROR,"文件删除失败或文件已删除！");
        }
    }


}
